package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.model.entity.system.SysMenu;
import com.atguigu.spzx.model.vo.system.SysMenuVo;

import java.util.ArrayList;
import java.util.List;

public class SysMenuHelper {


    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        List<SysMenu> sysMenuTree=new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            if(sysMenu.getParentId()==0){
                //如果是顶级菜单,那么加入集合里,加入之前需要递归找到子菜单,从所有菜单里找
                sysMenuTree.add(findChildren(sysMenu,sysMenuList));
            }
        }
        return sysMenuTree;
    }

    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) {
        //创建子菜单集合
        List<SysMenu> childrenMenu =new ArrayList<>();
        //找sysMenu的子菜单并复制
        for (SysMenu menu : sysMenuList) {
            if(menu.getParentId()==sysMenu.getId()){
                //找到子菜单加入子菜单集合里   //但在加入前先递归找子菜单的子菜单
                childrenMenu.add(findChildren(menu,sysMenuList));
            }
        }
        sysMenu.setChildren(childrenMenu);
        return sysMenu;
    }

    public static List<SysMenuVo> buildMenus(List<SysMenu> menuList) {
        List<SysMenuVo> sysMenuVoList=new ArrayList<>();
        //找到顶级结点, parentId=0的结点
        for (SysMenu menu : menuList) {
            if(menu.getParentId()==0){
                //找到父节点,向结果数组转移数据
                SysMenuVo sysMenuVo=new SysMenuVo();
                sysMenuVo.setName(menu.getComponent());
                sysMenuVo.setTitle(menu.getTitle());
                //递归赋值子结点,需要返回一个List<SysMenuVo>
                List<SysMenuVo> menuChildren= findChildren(menuList,menu.getId());
                sysMenuVo.setChildren(menuChildren);
                //把封装好的结点菜单添加进结果集合里
                sysMenuVoList.add(sysMenuVo);
            }
        }

        return sysMenuVoList;
    }

    private static List<SysMenuVo> findChildren(List<SysMenu> menuList, Long parentId) {
        List<SysMenuVo> childrenList=new ArrayList<>();
        for (SysMenu menu : menuList) {
            //找到父节点id=parentId的子结点
            if(menu.getParentId()==parentId){
                //找到父节点,向结果数组转移数据
                SysMenuVo sysMenuVo=new SysMenuVo();
                sysMenuVo.setName(menu.getComponent());
                sysMenuVo.setTitle(menu.getTitle());
                //递归赋值子结点,需要返回一个List<SysMenuVo>
                List<SysMenuVo> menuChildren= findChildren(menuList,menu.getId());
                sysMenuVo.setChildren(menuChildren);
                //把封装好的结点菜单添加进结果集合里
                childrenList.add(sysMenuVo);
            }
        }
        if(childrenList.size()==0){
            return null;
        }
        return childrenList;
    }
}
